
<script setup>
	
	import readApi from '@/common/apis/read';
	import useFont from './components/useFont';
	import xTitle from './components/title.vue';
	import { onHide, onShow } from '@dcloudio/uni-app';
	import dialog_font from './components/dialog_font.vue';
	import xQuestSingle from './components/questSingle.vue';
	import popupSubmit from './components/dialog_submit.vue';
	import { ref, computed, reactive, onBeforeUnmount, getCurrentInstance, nextTick } from 'vue';
	import { postSubmitExer_api, getExerDetail_api, postSaveAnswer_api, finishCourse } from '@/common/apis/course';
	
	
	/** props */
	const props = defineProps(['exerciseId', 'articleId', 'readTime', 'analyze']);
	
	/** 导航栏 margin-right */
	const navRight = ref(0);
	
	// #ifdef MP-WEIXIN
	/** 获取小程序胶囊信息 */
	const { width } = uni.getMenuButtonBoundingClientRect()
	navRight.value = `${width}px`;
	// #endif
	
	
	/** 练习详情 */
	const exerInfo = ref({});
	const getExerInfo = async () => {
		const result = await getExerDetail_api({ id: props.exerciseId });
		exerInfo.value = result;
	};
	
	/** 倒计时 */
	const answerTime = ref(0);
	
	/** 倒计时对象 */
	const answerTimer = ref(null);
	
	/** 增加计时 */
	const increaseReadTime = () => {
	    answerTime.value += 1;
	};
	
	/** 倒计时计算方法 */
	const formattedReadTime = computed(() => {
	    const minutes = Math.floor(answerTime.value / 60);
	    const seconds = answerTime.value % 60;
	    return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
	});
	
	/** 清楚答题倒计时 */
	const clearReadTimeInterval = () => {
		clearInterval(answerTimer.value);
		answerTimer.value = null;
	};
	
	/** 开启阅读倒计时方法 */
	const onInterval = () => {
		// const answerData = uni.getStorageSync('course:ai-reading:answer:time') || {};
		// if (answerData.exerciseId == props.exerciseId && answerData.articleId == props.articleId) {
		// 	answerTime.value = answerData.useTime || 0;
		// };
		
		answerTimer.value = setInterval(increaseReadTime, 1000)
	};
	
	
	/** 题目列表 */
	const info = ref({});
	
	/** 获取阅读详情方法 */
	const getInfo = async () => {
		// const result = await readApi.info({ readId: props.readId });
		info.value = uni.getStorageSync('aireading:article:questions');
		await getExerInfo();
		console.log('exerInfo', exerInfo.value);
		exerInfo.value.log.answer?.forEach?.((item, index) => {
			const findIndex = info.value.questions.findIndex(find => find.id === +item.id);
			if (item.answer?.length && !!~findIndex) {
				info.value.questions[findIndex].play = true;
				info.value.questions[findIndex].answer = item.answer;
				toggleSelection(+item.id, item.answer);
			};
		});
		
		if (props.analyze == 1) {
			info.value.questions.forEach(item => {
				if (!item.answer?.length) {
					item.noAnswer = true;
					item.answer = item.rightAnswer;
				};
			});
		};
	};
	
	/** 获取阅读详情 */
	getInfo();
	
	
	/** 答题索引 */
	const answerIndex = ref(0);
	
	/** swiper 滑动时 */
	const handleSwiper = event => {
		answerIndex.value = event.detail.current;
	};
	
	
	/** ai 文章弹窗实例 */
	const aiArticleRef = ref({});
	
	/** 答题卡弹窗实例 */
	const answerCardRef = ref({});
	
	/** 答案列表 */
	const answerslist = reactive([]);
	
	/** 提交弹窗状态 */
	const showPopupSubmit = ref(false);
	
	/** 选择 */
	const toggleSelection = (id, prefix, type) => {
		const existingIndex = answerslist.findIndex(answer => +answer.id === +id);
		if (!!~existingIndex) {
			const existingAnswer = answerslist[existingIndex].answer;
			existingAnswer.splice(0, existingAnswer.length);
			existingAnswer.push(prefix);
			answerslist[existingIndex].answer = existingAnswer;
			
		} else {
			answerslist.push({ id: id, answer: [prefix] });
		};
	};
	
	/** 答题 */
	const onAnswer = async (data, index, item) => {
		if (props.analyze == 1) return;
		info.value.questions[index].answer = data.answer;
		toggleSelection(item.id, data.answer);
		
		/** 所有答案 */
		setTimeout(() => {
			item.shake = true;
			if (answerIndex.value === info.value.questions.length - 1) {
				showPopupSubmit.value = true;
				
			} else {
				answerIndex.value++;
			};
			
		}, 1000);
		
		
		const answers = info.value?.questions.map(({ id, answer }) => ({ id, answer })).filter(item => item.answer?.length);
		await postSaveAnswer_api({ exerciseId: props.exerciseId, answers, logId: exerInfo.value.logId });
	};
	
	/** 是否已答 */
	const isAnswered = id => {
	    return answerslist.some(answer => answer.id === id);
	};
	
	/** 答题卡题点击 */
	const onCardAnswer = index => {
		answerIndex.value = index;
	};
	
	/** 提交 */
	const onSubmit = async () => {
		uni.showLoading({
			mask: true,
			title: '提交中...'
		});
		
		clearReadTimeInterval();
		await postSubmitExer_api({ exerciseId: props.exerciseId, logId: exerInfo.value.logId, useTime: answerTime.value });
		await finishCourse({ exerciseId: props.exerciseId, readTime: props.readTime });
		uni.redirectTo({ 
			url: `/pages/course/aireading/answer-report?id=${props.exerciseId}` 
		});
		uni?.hideLoading?.();
	};
	
	/** 答题卡提交 */
	const answerCardSubmit = () => {
		/** 所有答案 */
		const answers = info.value?.questions.map(({ id, answer }) => ({ id, answer })).filter(item => item.answer?.length);
		
		if (!answers.length) {
			uni.$fui.toast('请先答题哦');
			return false;
		};
		
		answerCardRef.value?.close();
		showPopupSubmit.value = true;
	};
	
	
	/** 设置字体 */
	const { fontStatus, font_title, font_cons, setupFontFun } = useFont();
	
	
	/** 文章段落 */
	const isTranslation = ref(false);
	const { proxy } = getCurrentInstance();
	const courseArticleParagraphlist = ref([]);
	const getCourseArticleParagraphs = async () => {
		const result = await readApi.courseArticleParagraphs({ articleId: props.articleId });
		courseArticleParagraphlist.value = result;
	};
	getCourseArticleParagraphs();
	
	/** AI 文章弹窗打开/关闭时 */
	const articleHandleChange = ({ show }) => {
		if (!show || courseArticleParagraphlist.value[0].rect) return;
		nextTick(() => {
			uni.createSelectorQuery()
				.in(proxy)
				.selectAll('.translation-view .translation-view-text')
				.boundingClientRect(result => {
					result.forEach((item, index) => {
						courseArticleParagraphlist.value[index].rect = item;
					});
				})
				.exec();
		});
	};
	
	
	/** String array flattening */
	const onStringArrayFlattening = (list = []) => {
		return list.reduce((str, item) => `${str}${item}、`, '').slice(0, -1);
	};
	
	
	/** unmount */
	const unmount = () => {
		if (props.analyze != 1) {
			// uni.setStorageSync('course:ai-reading:answer:time', { ...props, useTime: answerTime.value });
		};
	};
	
	onHide(unmount);
	onBeforeUnmount(unmount);
	onShow(() => {
		onInterval();
	});
	
	
</script>

<template>
	<view class="containerbox bgc-white" :style="'--font_title: '+font_title+'rpx;--font_cons:'+font_cons+'rpx'">
		<uv-navbar :left-text="props.analyze == 1 ? '' : '答题'" auto-back placeholder bg-color="transparent">
			<template v-slot:right>
				<view class="flex items-center pr-10" :style="{ marginRight: navRight }">
					<view class="flex flex-column justify-center items-center mr-20 text-18" v-if="props.analyze == 0">
						<image src="https://assets-1315727392.cos.ap-chongqing.myqcloud.com/yingyu/png/pic14.png" mode="heightFix" class="h-20" />
						{{ formattedReadTime }}
					</view>
					
					<image src="https://assets-1315727392.cos.ap-chongqing.myqcloud.com/yingyu/png/pic15.png" class="w-50 h-50 mr-20" @tap="answerCardRef.open" />
					
					<view class="px-10 -mr-10" @tap="fontStatus = !fontStatus">
						<image :src="`https://assets-1315727392.cos.ap-chongqing.myqcloud.com/questbank/png/pic16.png`" class="w-45 h-45" />
					</view>
				</view>
			</template>
		</uv-navbar>
		
		
		<view class="containerbox">
			<swiper class="containerbox" @change="handleSwiper" :current="answerIndex">
				<swiper-item v-for="item, index in info?.questions" :key="index">
					<scroll-view class="containerbox" scroll-y>
						<view class="px-30">
							<x-title :info="item" :length="item.option.length" :index="index" />
							<x-questSingle 
								v-bind="item"
								:isexam="false" 
								:list="item.option" 
								@on-play="item.play = true"
								:shake="props.analyze == 1 || !item.answer?.length" 
								@takeFun="onAnswer($event, index, item)" 
							/>
							
							<view class="h-80" />
							<uv-transition :show="props.analyze == 1">
								<view class="rd-12 p-30" style="background-color: rgba(243, 247, 250, .7)">
									<view class="text-28 flex items-center justify-between">
										<view class="flex items-center">
											正确答案：
											<text class="text-primary2 ml-8">{{ onStringArrayFlattening(item.rightAnswer) }}</text>
										</view>
										
										<view class="flex items-center">
											你的答案：
											<text 
												class="ml-8" 
												:class="!item.noAnswer && onStringArrayFlattening(item.rightAnswer) === onStringArrayFlattening(item.answer) ? 'text-primary2' : 'text-red'"
											>
												<template v-if="!item.noAnswer">{{ onStringArrayFlattening(item.answer) }}</template>
												<template v-else>未答</template>
											</text>
										</view>
									</view>
								</view>
								
								<view class="bg-F3F7FA rd-12 p-30 mt-30">
									<view class="text-28 lh-48">
										<text style="font-weight: bold">解析</text>
										<text>：{{ item?.analysis }}</text>
									</view>
								</view>
							</uv-transition>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
		
		
		<view class="view-buttom flex items-center justify-between">
			<view>
				<text class="text-green text-32">{{ answerIndex + 1 }}</text>
				<text class="mx-10 text-28">/</text>
				<text class="text-28">{{ info?.questions?.length || 0 }}</text>
			</view>
			
			<view class="w-30" />
			<view class="btn bgc-primary2" @tap="aiArticleRef.open" v-if="props.analyze == 0">查看原文</view>
		</view>
		
		
		
		<uv-popup mode="bottom" :safe-area-inset-bottom="false" round="32rpx" ref="aiArticleRef" @change="articleHandleChange">
			<view class="flex items-center justify-between pt-30 pb-40 px-30">
				<view class="text-36 font-weight-700">AI 文章</view>
				<uv-icon name="close" size="32rpx" @tap="aiArticleRef.close" />
			</view>
			
			<scroll-view scroll-y class="px-30 h-50vh">
				<template v-for="item in courseArticleParagraphlist" :key="item.id">
					<view style="line-height: 50rpx">{{ item.english }}</view>
					<view 
						class="translation-view" 
						style="overflow: hidden;transition: height .3s, opacity .3s" 
						:style="{ height: isTranslation ? `${item.rect?.height}px` : 0, opacity: Number(isTranslation) }"
					>
						<view style="line-height: 40rpx;font-size: 23rpx;color: #909399" class="translation-view-text">{{ item.chinese }}</view>
					</view>
					<view style="height: 35rpx;width: 100%" />
				</template>
			</scroll-view>
			
			<view class="cardbox">
				<view
					hover-class="botton-active"
					@click="isTranslation = !isTranslation"
					style="background-color: #00c386;color: white;margin-left: auto"
					class="w-90 h-90 bgc-white round-30 flex items-center relative justify-center text-34" 
				>
					译
				</view>
			</view>
		</uv-popup>
		
		
		<uv-popup mode="bottom" :safe-area-inset-bottom="false" round="32rpx" ref="answerCardRef">
			<view class="flex items-center justify-between pt-30 pb-40 px-30">
				<view class="text-36 font-weight-700">答题卡</view>
				<uv-icon name="close" size="32rpx" @tap="answerCardRef.close" />
			</view>
			
			<view class="cardbox">
				<view class="box">
					<view class="item" v-for="item, index in info?.questions" :key="index" :class="{ selected: isAnswered(item.id) }" @tap="onCardAnswer(index)">{{ index + 1 }}</view>
				</view>
				
				<view class="text-22 text-gray-80 text-center mt-50" v-if="info?.questions?.filter?.(item => !item.answer?.length).length">
					<text>你有{{ info?.questions?.filter?.(item => !item.answer?.length).length }}道未完成的题目，请注意检查试卷</text>
				</view>
				
				<view class="btn bgc-primary2 mt-100" @tap="answerCardSubmit" v-if="props.analyze == 0">提交</view>
			</view>
		</uv-popup>
		
		<dialog_font v-model="fontStatus" @callback="setupFontFun" />
		<popup-submit :list="info?.questions" v-model="showPopupSubmit" @submit="onSubmit" />
	</view>
</template>


<style scoped lang="scss">
	.h-50vh{height: 50vh}
	.lh-70{line-height: 70rpx}
	.pb-24{padding-bottom: 24rpx}
	.view-buttom{padding: 8rpx 30rpx 24rpx}
	.progress{border-radius: 100%; box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.05)}
	.btn{height: 90rpx;border-radius: 30rpx;width: 200rpx;color: #fff;font-size: 32rpx;display: flex;align-items: center;justify-content: center}
	.btn.mt-100{width: 100%}
	.cardbox{padding: 30rpx 32rpx 60rpx}
	.cardbox .box{display: flex;flex-wrap: wrap}
	.cardbox .box .item{margin-right: 20rpx;width: 60rpx;height: 60rpx;background-color: #f5f5f5;border-radius: 100%; order: 2rpx solid #f5f5f5;font-size: 26rpx;display: flex;align-items: center;justify-content: center}
	.cardbox .box .item.selected{background-color: $primary2; color: #fff}
</style>